﻿using Newtonsoft.Json.Linq;
using S2_Xxxx_XxxNetApi;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace S2_Xxxx_XxxNetApi.Handle
{
    public static class CommonHandle
    {
        /// <summary>
        /// 根据用户ID获取组织架构路径
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public static JObject GetDeptFulllPath(string UserId)
        {
            JObject jReturn = new JObject();
            jReturn["result"] = "error";
            string deptIdPath = string.Empty;
            string deptNamePath = string.Empty;
            string sql = string.Format("SELECT ParentID FROM t_user WHERE ObjectID='{0}'", UserId);
            DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql, null);
            if (dt.Rows.Count > 0)
            {
                string parentId = dt.Rows[0]["ParentID"].ToString();
                while (!string.IsNullOrEmpty(parentId) && parentId != "18f923a7-5a5e-426d-94ae-a55ad1a4b240")
                {
                    string xhsql = string.Format("SELECT Name,ObjectID,ParentID FROM t_organization_unit WHERE ObjectID='{0}'  ", parentId);
                    DataTable xhdt = MySqlHelper.GetDataTable(CommandType.Text, xhsql, null);
                    if (xhdt.Rows.Count > 0)
                    {
                        string deptName = xhdt.Rows[0]["Name"].ToString();
                        string deptId = xhdt.Rows[0]["ObjectID"].ToString();
                        string nparentId = xhdt.Rows[0]["ParentID"].ToString();
                        deptIdPath = "/" + deptId + deptIdPath;
                        deptNamePath = "/" + deptName + deptNamePath;
                        parentId = nparentId;
                    }
                }
                jReturn["result"] = "sucess";
                jReturn["deptIdPath"] = deptIdPath.Trim('/');
                jReturn["deptNamePath"] = deptNamePath.Trim('/');
            }
            return jReturn;
        }


        /// <summary>
        /// 根据部门ID获取部门及子部门是否存在用户
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public static JObject GetDeptHaveUser(string unitId)
        {
            JObject jReturn = new JObject();
            jReturn["result"] = "error";
            string deptIdPath = string.Empty;
            string deptNamePath = string.Empty;
            string sql = string.Format("SELECT ParentID FROM t_user WHERE ParentId='{0}'", unitId);
            DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql, null);
            if (dt.Rows.Count > 0)
            {
                string parentId = dt.Rows[0]["ParentID"].ToString();
                while (!string.IsNullOrEmpty(parentId) && parentId != "18f923a7-5a5e-426d-94ae-a55ad1a4b240")
                {
                    string xhsql = string.Format("SELECT Name,ObjectID,ParentID FROM t_organization_unit WHERE ObjectID='{0}'  ", parentId);
                    DataTable xhdt = MySqlHelper.GetDataTable(CommandType.Text, xhsql, null);
                    if (xhdt.Rows.Count > 0)
                    {
                        string deptName = xhdt.Rows[0]["Name"].ToString();
                        string deptId = xhdt.Rows[0]["ObjectID"].ToString();
                        string nparentId = xhdt.Rows[0]["ParentID"].ToString();
                        deptIdPath = "/" + deptId + deptIdPath;
                        deptNamePath = "/" + deptName + deptNamePath;
                        parentId = nparentId;
                    }
                }
                jReturn["result"] = "sucess";
                jReturn["deptIdPath"] = deptIdPath.Trim('/');
                jReturn["deptNamePath"] = deptNamePath.Trim('/');
            }
            return jReturn;
        }


        public static string ToMD5(this string str)
        {
            try
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(str)));
                t2 = t2.Replace("-", "");
                return t2;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return str;
        }


        #region  尝试不用递归生成树（更简洁高效）  
        public class Organization
        {
            public string Id { get; set; }
            public string Code { get; set; }
            public string Name { get; set; }
            public string Pid { get; set; }
            public List<Organization> Children { get; set; }
            public DataTable UserList { get; set; }
        }

        public static List<Organization> GetOrgnaizeList(string orgId, bool childOrg, bool ckUser, bool ckChildUser)
        {
            List<Organization> resultList = new List<Organization>();
            string sql = @"SELECT A.ObjectID,A.NAME,A.Code,A.ParentID FROM t_organization_unit A ";
            sql += string.Format(" WHere A.ObjectID='{0}'", orgId);
            DataTable orgDt = MySqlHelper.GetDataTable(CommandType.Text, sql, null);
            string userSql = @"select ObjectID,Name,Code,Email,Mobile  from t_user where ParentId='{0}' and State='1' ";
            for (int i = 0; i < orgDt.Rows.Count; i++)
            {
                Organization entity = new Organization();
                entity.Id = orgDt.Rows[i]["ObjectID"].ToString();
                entity.Code = orgDt.Rows[i]["Code"].ToString();
                entity.Name = orgDt.Rows[i]["Name"].ToString();
                entity.Pid = orgDt.Rows[i]["ParentID"].ToString();
                if (ckUser)
                {
                    userSql = string.Format(userSql, entity.Id);
                    DataTable userDt = MySqlHelper.GetDataTable(CommandType.Text, userSql, null);
                    entity.UserList = userDt;
                }
                if (childOrg)
                {
                    var d = creatOrgnaizeTree(entity.Id, entity, ckChildUser);
                    if (d == null)
                    {
                        resultList.Add(entity);
                        continue;
                    }
                    resultList.Add(d);
                }
                else
                    resultList.Add(entity);
            }
            return resultList;
        }


        //生成树的方法(自身方法不断循环)
        public static Organization creatOrgnaizeTree(string parentId, Organization jd, bool ckUser)
        {
            string sql = @"SELECT A.ObjectID,A.NAME,A.Code,A.ParentID FROM t_organization_unit A ";
            sql += string.Format(" WHere A.ParentID='{0}'", parentId);
            DataTable orgDt = MySqlHelper.GetDataTable(CommandType.Text, sql, null);
            string userSql = @"select ObjectID,Name,Code,Email,Mobile  from t_user where ParentId='{0}' ";
            //如果没有字节点了，那就返回空
            if (orgDt.Rows.Count == 0)
                return null;
            List<Organization> jdList = new List<Organization>();
            for (int i = 0; i < orgDt.Rows.Count; i++)
            {
                Organization entity = new Organization();
                entity.Id = orgDt.Rows[i]["ObjectID"].ToString();
                entity.Code = orgDt.Rows[i]["Code"].ToString();
                entity.Name = orgDt.Rows[i]["Name"].ToString();
                entity.Pid = orgDt.Rows[i]["ParentID"].ToString();
                if (ckUser)
                {
                    userSql = string.Format(userSql, entity.Id);
                    DataTable userDt = MySqlHelper.GetDataTable(CommandType.Text, userSql, null);
                    entity.UserList = userDt;
                }
                //递归循环
                creatOrgnaizeTree(entity.Id, entity, ckUser);
                jdList.Add(entity);
            }
            jd.Children = jdList.ToList(); //由于对象是引用类型，因为可以改变参数的值
            return jd;
        }

        public static DataTable GetUserInfo(string UserId, string Code, string Mobile, string Email)
        {
            string sql = @"SELECT t.ObjectID,t.Name,t.Code,t.Email,t.Mobile,u.Name OrgName,u.Code OrgCode,u.ObjectID OrgId FROM t_user t LEFT JOIN t_organization_unit u on t.ParentID=u.ObjectID where 1=1 ";
            if (UserId.IsNotNullOrEmpty()) 
            {
                sql += string.Format("and t.ObjectID='{0}' ", UserId);
            }
            if (Code.IsNotNullOrEmpty())
            {
                sql += string.Format("and t.Code='{0}' ", Code);
            }
            if (Mobile.IsNotNullOrEmpty())
            {
                sql += string.Format("and t.Mobile='{0}' ", Mobile);
            }
            if (Email.IsNotNullOrEmpty())
            {
                sql += string.Format("and t.Email='{0}' ", Email);
            }
            DataTable userDt = MySqlHelper.GetDataTable(CommandType.Text, sql, null);
            return userDt;
        }


        #endregion

    }
}
